package com.wangp.mywrite.inwork.classloader;

import static org.springframework.util.FileCopyUtils.copy;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;

/***
 * @author wangpeng
 * @since 2022-02-23  11:08
 */
public class MyClassLoader extends ClassLoader {

    private static final String BASE_DIR = "D:\\project\\MyWriter\\src\\main\\java\\com\\wangp\\mywrite\\inwork\\classloader\\data\\";

    @Override
    protected Class<?> findClass(String name) {
        String fileName = name.replaceAll("\\.", "/");
        fileName = BASE_DIR + fileName + ".class";

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(fileName);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            copy(fileInputStream, byteArrayOutputStream);
            byte[] bytes = byteArrayOutputStream.toByteArray();

            return defineClass(name, bytes, 0, bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
